package com.zzzzzz.config;

import javax.inject.Inject;

import org.apache.tomcat.jdbc.pool.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class DataConfig {
	
	@Inject
	private DataSource dataSource;
	
	@Bean
	public NamedParameterJdbcTemplate jt() {
		return new NamedParameterJdbcTemplate(dataSource);
	}
	
	@Bean   
	public DataSourceTransactionManager txManager() {
	    return new DataSourceTransactionManager(dataSource);
	}
	
	@Configuration
	static class Standard {

		@Inject
		private Environment environment;

		@Bean(destroyMethod="close")
		public DataSource dataSource() {
			DataSource dataSource = new DataSource();
			dataSource.setDriverClassName(environment.getProperty("jdbc.driver"));
			dataSource.setUrl(environment.getProperty("jdbc.url"));
			dataSource.setUsername(environment.getProperty("jdbc.username"));
			dataSource.setPassword(environment.getProperty("jdbc.password"));
			
			dataSource.setInitialSize(5);
			dataSource.setMinIdle(5);
			dataSource.setMaxIdle(10);
			dataSource.setMaxActive(15);
			dataSource.setTestOnBorrow(true);
			dataSource.setValidationQuery("select 1");
			dataSource.setValidationInterval(30000);
			
			return dataSource;
		}
	}
}
